package controller

import (
	"log"
	"strconv"
	"strings"
	"time"
	"user-agent/database/bean"
	"user-agent/database/myredis"
	"user-agent/database/schema"
	"user-agent/utils"

	"github.com/huyinghuan/encryption"
	"github.com/kataras/iris/context"
)

type authorziedCtrl struct {
	AliveModel *bean.AliveBean
}

var AuthorziedCtrl = &authorziedCtrl{
	&bean.AliveBean{},
}

func (ctrl *authorziedCtrl) Get(ctx context.Context) {
	key := ctx.GetHeader("Authorization")
	if key == "" {
		ctx.StatusCode(403)
		return
	}
	id := strings.Replace(key, "_", ".", -1)
	id = strings.Replace(id, "$", ":", -1)
	if err := ctrl.AliveModel.Insert(&schema.Alive{
		Mac: id,
	}); err != nil {
		log.Println(err)
	}
	go func(id string) {
		myredis.SAdd("vps", id)
		myredis.HMSet("vps:"+id, "time", time.Now().Unix(), "id", id)
		myredis.HIncr("vps:"+id, "count")
	}(id)

	if !utils.GetConfig().Authorized {
		ctx.StatusCode(200)
		return
	}
	now := strconv.FormatInt(time.Now().Unix(), 10)
	responseText := now + "," + "pass"
	cbc := encryption.CBC(key)
	if result, err := cbc.EncryptString(responseText); err != nil {
		ctx.StatusCode(500)
	} else {
		ctx.WriteString(result)
	}
}
